package vip.zhenzicheng.nettybasic.embedded;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException;

import java.util.List;

/**
 * 扩展实现将入站字节解码为消息
 *
 * @author zhenzicheng
 * @date 2022-06-13 11:56
 */
public class FrameChunkDecoder extends ByteToMessageDecoder {

  private final int maxFrameSize;

  public FrameChunkDecoder(int maxFrameSize) {
    this.maxFrameSize = maxFrameSize;
  }

  @Override
  protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
    int readableBytes = byteBuf.readableBytes();
    if (readableBytes > maxFrameSize) { // 如果该帧超出允许大小，则丢弃并抛出异常
      byteBuf.clear();
      throw new TooLongFrameException();
    }
    ByteBuf buf = byteBuf.readBytes(readableBytes);
    list.add(buf);
  }
}
